﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ServiceModel;
using System.Windows.Forms;

namespace HobSoft.SoccerBet2014.Server
{
    using Domain.ClientService;
    using Domain.Common.SiteContext;
    using Domain.Implementation;
    using Domain.IRepositories;
    using Domain.Models;
    using Domain.Models.Site;
    public partial class SiteContextSyncDialog : Form
    {
        private readonly ICookiesManager cookieManager;
        private readonly ISiteContextRepository siteContextRepository;
        public SiteContextSyncDialog(ICookiesManager _cookieManager, ISiteContextRepository _siteContextRepository)
        {
            cookieManager = _cookieManager;
            siteContextRepository = _siteContextRepository;
            InitializeComponent();
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Hide();
        }

        private void btnSubmit_Click(object sender, EventArgs e)
        {
            var redisCookieManager = cookieManager as ReadWriteRedisRepository<AccountCookie>;
            var redisSiteContext = siteContextRepository as ReadWriteRedisRepository<SiteContext>;
            if (string.IsNullOrEmpty(txtRemoteService.Text))
            {
                MessageBox.Show("请输入远程服务地址");
                return;
            }

            string serviceUri = txtRemoteService.Text;
            EndpointAddress address = new EndpointAddress(serviceUri);
            WS2007HttpBinding binding = new WS2007HttpBinding();
            binding.Security.Mode = SecurityMode.None;
            binding.MaxReceivedMessageSize = 2147483647;
            using (var remoteService = new ChannelFactory<ISystemService>(binding, address))
            {
                remoteService.Open();
                var remoteSysService = remoteService.CreateChannel();
                if (redisCookieManager != null)
                {
                    var cookies = redisCookieManager.GetMany(c => true);
                    remoteSysService.SubmitCookies(cookies);
                }
                if (redisSiteContext != null)
                {
                    var siteContexts = redisSiteContext.GetMany(s => true);
                    remoteSysService.SubmitSiteContext(siteContexts);
                }
                remoteService.Close();
            }
            MessageBox.Show("同步成功");
        }
    }
}
